﻿/*
 * logmonitormgr.cpp
 *
 *  Created on: 2019-1-11
 *      Author: Dylan.Gao
 */

#include <dm/export.hpp>
#define DM_API_SESSION DM_API_EXPORT

#include <dm/session/logmonitormgr.hpp>
#include <dm/session/modgen.hpp>

#include <dm/os/log/logger.hpp>

static const char* logModule = "CLogMonitorMgr.session.dm";

namespace dm{
namespace session{

CLogMonitorMgr::CLogMonitorMgr():m_lock(){
	log().debug(THISMODULE "Size:%d",Size);
}

CLogMonitor* CLogMonitorMgr::getNew( dm::CTimeStamp::s_t aliveSec ){
	msharelock_exclusive_t ml(m_lock);
	dm::CTimeStamp n = dm::CTimeStamp::cur();
	for( int i=0;i<Size;++i ){
		if( m_d[i].isIdle(n) ){
			n.setSeconds( n.seconds() + aliveSec );
			m_d[i].setDeadline(n);
			m_d[i].setMod(CModGen::ins().gen());

			log().debug(THISMODULE "分配新的监视器%llX",m_d[i].mod());

			return m_d + i;
		}
	}

	log().warnning(THISMODULE "分配新的监视器失败");

	return NULL;
}

CLogMonitor* CLogMonitorMgr::get( mod_t mod,dm::CTimeStamp::s_t aliveSec ){
	msharelock_exclusive_t ml(m_lock);
	dm::CTimeStamp n = dm::CTimeStamp::cur();
	for( int i=0;i<Size;++i ){
		if( m_d[i].mod()==mod ){
			if( m_d[i].isTimeout(n) ){
				log().warnning(THISMODULE "监视器%llX过期",mod);
				return NULL;
			}else{
				if( aliveSec>0 ){
					n.setSeconds(n.seconds()+aliveSec);// 防止其他进程利用
					m_d[i].setDeadline(n);
				}
				return m_d + i;
			}
		}
	}

	log().warnning(THISMODULE "未找到监视器%llX",mod);
	return NULL;
}

void CLogMonitorMgr::free( mod_t mod ){
	msharelock_exclusive_t ml(m_lock);
	for( int i=0;i<Size;++i ){
		if( m_d[i].mod()==mod ){
			m_d[i].setMod(0);
			return;
		}
	}
}

}
}
